const cheerio = require('cheerio');
const fs = require('fs');
const path = require('path');
const Sheet = require('../language_json/Sheet');
const { defaultLanguage } = require('../config');;

const filePath = path.join(__dirname, '../source');
const fileNames = fs.readdirSync(filePath);

const languageObjModal = {
    "English": "en",
    "Chinese": "cn",
    "Bahasa Indonesia": "id",
    "Thai": "th",
    "Vietnamese": "vn",
    "Japanese": "jp",
    "Spanish": "es",
    "Portuguese": "pt"
}
function getLanguageObj(languageKey) {
    let data = {}
    for (let item of Sheet) {
        data[item.English] = item[languageKey]
    }
    return data
}
// 批量替换语言
function replaceLanguage(file, languageObj, outputFilePath, key) {
    const $ = cheerio.load(file);
    // 遍历所有文本节点，进行替换
    let rule = '*:not(script)'
    rule = '*'
    $(rule).contents().each((index, element) => {
        console.log("element==", element.nodeValue, '==', element.nodeType);
        if (element.nodeType === 3) { // 文本节点
            let originalText = element.nodeValue;
            let originalTextTrim = originalText.trim();
            let newTextTrim = languageObj[originalTextTrim];
            if (newTextTrim) {
                console.log("originalTextTrim==", originalTextTrim);
                let newText = originalText.replace(originalTextTrim, originalTextTrim);
                element.nodeValue = newText;
            }
        }
    });
    const result = $.html();
    const outputFileFatherPath = path.join(__dirname, `../output/${languageObjModal[key]}`);
    console.log("outputFileFatherPath==", outputFileFatherPath);
    if (fs.existsSync(outputFilePath)) {
        fs.unlinkSync(outputFilePath);
    }
    fs.writeFile(outputFilePath, result, 'utf-8', (err) => {
        if (err) {
            console.log(`${outputFilePath} replacement successful`)
        } else {
            console.log(`${outputFilePath} replacement failed` + err)
        }
    });
}
function init() {
    // 遍历文件列表
    fileNames.forEach((fileName) => {
        const filePath = path.join(__dirname, `../source/${fileName}`);
        // 拿到html文件的字符串
        const Sheet = fs.readFileSync(filePath, 'utf-8');
        // console.log("Sheet==", Sheet);
        for (let key in languageObjModal) {
            const outputFilePath = path.join(__dirname, `../output/${languageObjModal[key]}/${fileName}`);
            replaceLanguage(Sheet, getLanguageObj(key), outputFilePath, key);
        }
    });
}
init()

